package cn.client.ui.view.signUp

import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.NavGraph.Companion.findStartDestination
import cn.client.R
import cn.client.navigation.destinations.SignInFirst
import cn.client.ui.view.signUp.SignUpViewModel
import kotlinx.coroutines.launch

/**
 * 注册：第三步
 */
@Composable
fun SignUpThirdPage(
    account: String,
    navController: NavController,
    viewModel: SignUpViewModel = hiltViewModel()
) {

    val context = LocalContext.current
    var pwd: String by remember { mutableStateOf("") }
    var pwdAgain: String by remember { mutableStateOf("") }
    var passwordHidden by remember{ mutableStateOf(true)}  // 默认隐藏
    val coroutineScope = rememberCoroutineScope()
    // 观察ViewModel中的状态
    val states = viewModel.pageStates

    //  使用LaunchedEffect来启动协程，收集事件
    LaunchedEffect(Unit){
        viewModel.pageEvents.collect {
            if (it is SignUpViewModel.PageEvent.ThirdRes){
                if (it.res.code==200) {
                    Toast.makeText(context, "注册成功", Toast.LENGTH_LONG).show()
//                    navController.popBackStack(navController.graph.findStartDestination().id, true)
                    navController.navigate(route = SignInFirst.route)
                } else {
                    Toast.makeText(context,"注册失败 ${states.verifyStatus}", Toast.LENGTH_LONG).show()
                }
            } else if (it is SignUpViewModel.PageEvent.Error){
                Toast.makeText(context,"未知错误：${it.error}", Toast.LENGTH_LONG).show()
            }
        }
    }

    Box(
        contentAlignment = Alignment.Center,
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White)
    ){
        Column(
            modifier = Modifier.wrapContentSize(Alignment.Center, false)
        ) {
            /* 间隔距离 */
            Spacer(modifier = Modifier.height(40.dp))
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentSize(Alignment.Center, false)
            ) {
                Text(
                    text = (stringResource(R.string.sign_up)),
                    fontSize = 30.sp, // 字体大小
                    fontWeight = FontWeight.Bold,
                    textAlign = TextAlign.Center,
                )
            }
            /* 间隔距离 */
            Spacer(modifier = Modifier.height(30.dp))
            /* 输入密码 */
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentSize(Alignment.Center, false)
            ) {
                OutlinedTextField(
                    value = pwd,
                    label = {  Text(stringResource(R.string.password)) },
                    onValueChange = { str -> pwd = str },
                    placeholder = { Text(stringResource(R.string.input_pwd)) },
                    singleLine = true,
                    trailingIcon = {
                        IconButton(
                            onClick = { passwordHidden = !passwordHidden }
                        ) {
                            if (passwordHidden){
                                Icon(painterResource(id = R.drawable.ic_preview_close_one), null)
                            } else {
                                Icon(painterResource(id = R.drawable.ic_preview_open), null)
                            }
                        }
                    },
                    visualTransformation = if (passwordHidden) PasswordVisualTransformation() else VisualTransformation.None,
                    // 键盘事件
                    keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done),
                    keyboardActions = KeyboardActions(onDone = { }),
                    modifier = Modifier
                        .clip(RoundedCornerShape(20.dp))
                        .fillMaxWidth()
                        .padding(10.dp)
                )
            }
            /* 间隔距离 */
            Spacer(modifier = Modifier.height(20.dp))
            /* 确认密码 */
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentSize(Alignment.Center, false)
            ) {
                OutlinedTextField(
                    value = pwdAgain,
                    label = {  Text(stringResource(R.string.pwd_again)) },
                    onValueChange = { str -> pwdAgain = str },
                    placeholder = { Text(stringResource(R.string.input_pwd_again)) },
                    singleLine = true,
                    trailingIcon = {
                        IconButton(
                            onClick = { passwordHidden = !passwordHidden }
                        ) {
                            if (passwordHidden){
                                Icon(painterResource(id = R.drawable.ic_preview_close_one), null)
                            } else {
                                Icon(painterResource(id = R.drawable.ic_preview_open), null)
                            }
                        }
                    },
                    visualTransformation = if (passwordHidden) PasswordVisualTransformation() else VisualTransformation.None,
                    // 键盘事件
                    keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done),
                    keyboardActions = KeyboardActions(onDone = { }),
                    modifier = Modifier
                        .clip(RoundedCornerShape(20.dp))
                        .fillMaxWidth()
                        .padding(10.dp)
                )
            }
            /* 间隔距离 */
            Spacer(modifier = Modifier.height(20.dp))
            /* 下一步 */
            Row {
                Button(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(10.dp),
                    onClick = {
                        if (pwd !="" && pwdAgain != ""){
                            // 在协程中发送意图
                            coroutineScope.launch {
                                if (pwd != pwdAgain){
                                    Toast.makeText(context,"密码不一致", Toast.LENGTH_LONG).show()
                                } else {
                                    Toast.makeText(context,"已发送请求", Toast.LENGTH_SHORT).show()
                                    viewModel.dispatch(SignUpViewModel.PageIntent.VerifyPwd(account, pwd))
                                }
                            }
                        } else {
                            // 如果输入的内容为空，弹窗提示
                            coroutineScope.launch {
                                Toast.makeText(context,"密码不能为空", Toast.LENGTH_LONG).show()
                            }
                        }
                    },
                ) {
                    Text(
                        text = "提 交",
                        textAlign = TextAlign.Center
                    )
                }
            }
        }
    }
}